<?php
/******************************************************************************
*                                                                             *
* Steak Desk v0.2                                                             *
*                                                                             *
* Copyright (c) 2011 Andrew D. Zonenberg.                                     *
* All rights reserved.                                                        *
*                                                                             *
* Redistribution and use in source and binary forms, with or without modifi-  *
* cation, are permitted provided that the following conditions are met:       *
*                                                                             *
*    * Redistributions of source code must retain the above copyright notice  *
*      this list of conditions and the following disclaimer.                  *
*                                                                             *
*    * Redistributions in binary form must reproduce the above copyright      *
*      notice, this list of conditions and the following disclaimer in the    *
*      documentation and/or other materials provided with the distribution.   *
*                                                                             *
*    * Neither the name of the author nor the names of its contributors may be*
*      used to endorse or promote products derived from this software without *
*      specific prior written permission.                                     *
*                                                                             *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR IMPLIED *
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF        *
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN     *
* NO EVENT SHALL THE AUTHOR BE HELD LIABLE FOR ANY DIRECT, INDIRECT,          *
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT*
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, *
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF   *
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING        *
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS          *
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                *
*                                                                             *
*******************************************************************************/

require_once('../inc/utils.php');

function main()
{
	global $g_tplvars;
	$g_tplvars['title'] = 'Inventory';
		
	if(!isset($_GET['action']))
	{
		header('Location: inventory.php?action=browse');
		exit;
	}
	
	//actions which only need read permissions
	$read_actions = array(
		'',
		'summary',
		'browse',
		'detail',
		'itemdetail',
		'vendordetail',
		'orders',
		'orderdetail',
		'datasheets',
		'datasheetdownload',
		);
	
	//Look up our access
	restricted();
	if( in_array($_GET['action'], $read_actions) )
		checkinvaccess('read');
	else
		checkinvaccess('full');
	
	//legal actions
	$actions = array(
		'summary',
		'browse',
		'catalog',
		'createitem',
		'docreateitem',
		'vendors',
		'createvendor',
		'docreatevendor',
		'itemdetail',
		'createvendoritem',
		'docreatevendoritem',
		'createquote',
		'docreatequote',
		'vendordetail',
		'orders',
		'createorder',
		'docreateorder',
		'orderdetail',
		'addorderitem',
		'doaddorderitem',
		'datasheets',
		'datasheetdownload',
		'createdatasheet',
		'docreatedatasheet',
		'createitemdatasheet',
		'docreateitemdatasheet',
		'moveorderitem',
		);
		
	if(!in_array($_GET['action'], $actions))
		summary();
	else
		$_GET['action']();
}

function summary()
{
	global $g_tplvars;
	
	$startpage = intval($_GET['start']);
	$pagelen = 25;
	$pagelen = 25;
	if(isset($_GET['count']))
		$pagelen = intval($_GET['count']);
	
	//Get name of package enum
	$r = dbquery('select `id` from enums where name = \'packages\'');
	$pkg = mysql_fetch_object($r)->id;
	$delivered = enum_name_to_value('orderstatus', 'Delivered');
	
	//Apply filters
	$filters = '';
	$g_tplvars['filter'] = 'none';
	if(intval($_GET['cat']) > 0)
	{
		$cat = intval($_GET['cat']);
		$filters .= 'and items.cat = ' . $cat . ' ';
		
		$r = dbquery('select name from itemcats where `id` = ' . $cat);
		$catname = mysql_fetch_object($r)->name;		
		$g_tplvars['filter'] = 'cat = ' . $catname;
		
		$g_tplvars['title'] = 'Inventory :: ' . $catname;
	}
	if(intval($_GET['subcat']) > 0)
	{
		$subcat = intval($_GET['subcat']);
		$filters .= 'and items.subcat = ' . $subcat . ' ';
		
		$r = dbquery('select name from itemsubcats where `id` = ' . $subcat);
		$catname = mysql_fetch_object($r)->name;		
		
		$g_tplvars['title'] = 'Inventory :: ' . $catname;
		$g_tplvars['filter'] = 'subcat = ' . $catname;
	}
	if(intval($_GET['alertonly']))
	{
		$filters .= 'and items.stock and items.reorder >= items.count ';
		$g_tplvars['filter'] = 'low stock';
	}
	
	//Display it
	$inventory = '';
	$r = dbquery('select items.count, items.reorder, items.id, items.name, enumvals.name as pack, ' . 
				'itemcats.name as category, itemsubcats.name as subcategory, items.cat as catid, items.subcat as subcatid, '.
					'(select sum(orderitems.count) from orderitems, orders where orders.status != ' . $delivered . 
					' and orderitems.order = orders.id and orderitems.item = items.id) as onorder, ' .
				'items.stock from items, enumvals, itemcats, itemsubcats ' .
				'where items.pkg = enumvals.val and enumvals.eid = '. $pkg . ' ' .
				'and itemcats.id = items.cat and itemsubcats.id = items.subcat ' .
				$filters .
				'order by category, subcategory, name asc ' . 
				'limit ' . $startpage . ', ' . ($pagelen+1));
	while($row = mysql_fetch_assoc($r))
	{
		foreach($row as $a=>$b)
			$g_tplvars[$a] = $b;
		
		if($row['stock'])
		{
			$g_tplvars['stock'] = 'yes';
			if($row['count'] <= $row['reorder'])
				$g_tplvars['class'] = 'class=\'red\'';
			else
				$g_tplvars['class'] = '';
		}
		else
		{
			$g_tplvars['stock'] = 'no';
			$g_tplvars['class'] = '';
		}
		
		if(isset($_GET['subcat']) && $_GET['subcat'] != 0)
			$inventory .= templatize('../templates/inventory-summary-item-subcatset.html');
		else if(isset($_GET['cat']) && $_GET['cat'] != 0)
			$inventory .= templatize('../templates/inventory-summary-item-catset.html');
		else
			$inventory .= templatize('../templates/inventory-summary-item.html');
	}
	$g_tplvars['inventory'] = $inventory;
	
	//if we have more results
	if(mysql_num_rows($r) >= $pagelen)
	{
		$g_tplvars['nextstart'] = $startpage + $pagelen;
		$g_tplvars['nextcapt'] = 'next page';
	}
	else
	{
		$g_tplvars['nextstart'] = $startpage;
		$g_tplvars['nextcapt'] = '';
	}
	if($startpage > 0)
	{
		$g_tplvars['prevstart'] = max(0, $startpage - $pagelen);
		$g_tplvars['prevcapt'] = 'prev page';
	}
	else
	{
		$g_tplvars['prevstart'] = 0;
		$g_tplvars['prevcapt'] = '';
	}
	
	
	$g_tplvars['alertonly'] = intval($_GET['alertonly']);
	$g_tplvars['catid'] = intval($_GET['cat']);
	$g_tplvars['subcatid'] = intval($_GET['subcat']);
	$g_tplvars['navbar'] = templatize('../templates/inventory-summary-navbar.html');
	
	render('../templates/inventory-summary.html');
}

function createitem()
{
	global $g_tplvars;
	$g_tplvars['pkg'] = enum_list('packages');
	
	//List categories	
	$subcats = '';
	$r = dbquery('select itemsubcats.id as id, itemcats.name as cat, itemsubcats.name as subcat from itemcats, itemsubcats ' .
				'where itemcats.id = itemsubcats.parent order by cat asc, subcat asc');
	while($row = mysql_fetch_object($r))
	{
		$g_tplvars['value'] = $row->id;
		$g_tplvars['name'] = $row->cat . ' - ' . $row->subcat;
		$subcats .= templatize('../templates/enum-selector-line.html');
	}
	
	$g_tplvars['subcats'] = $subcats;	
	render('../templates/inventory-newitem.html');
}

function docreateitem()
{
	//Prepare input
	$desc = sanitize_db(sanitize_render($_POST['desc']));
	$pkg = intval($_POST['pkg']);
	$subcat = intval($_POST['subcat']);
	$count = intval($_POST['qty']);
	$reorder = intval($_POST['reorder']);
	$stock = 0;
	if($_POST['stock'] == 'on')
		$stock = 1;
	
	//Calculate category
	$r = dbquery('select parent from itemsubcats where `id` = ' . $subcat);
	$cat = mysql_fetch_object($r)->parent;
		
	//Insert it and continue
	dbquery('insert into items (`name`, `pkg`, `cat`, `subcat`, `count`, `reorder`, `stock`) ' .
			'values(\''.$desc.'\', \''.$pkg.'\', \''.$cat.'\', \''.$subcat.'\', \''.$count.'\', \''.$reorder.'\', \''.$stock.'\')');
	header('Location: inventory.php?action=summary');
}

function browse()
{
	global $g_tplvars;
	
	$r = dbquery('select `name`, `id` from itemcats order by name asc');
	$items = '';
	while($cat = mysql_fetch_object($r))
	{
		$s = dbquery(
			'select itemsubcats.name, itemsubcats.id, (select count(items.id) from items where items.subcat = itemsubcats.id) as ct ' . 
			'from itemsubcats where itemsubcats.parent = ' . $cat->id . ' order by name asc');		
		$cats = '';
		while($sub = mysql_fetch_object($s))
		{
			$g_tplvars['name'] = $sub->name;
			$g_tplvars['id'] = $sub->id;
			$g_tplvars['count'] = $sub->ct;
			$cats .= templatize('../templates/inventory-browser-subcat.html');
		}
		
		$t = dbquery('select count(`id`) as count from items where cat = ' . $cat->id);
		$g_tplvars['count'] = mysql_fetch_object($t)->count;
		$g_tplvars['cats'] = $cats;
		$g_tplvars['name'] = $cat->name;
		$g_tplvars['id'] = $cat->id;
		$items .= templatize('../templates/inventory-browser-category.html');
	}
	
	$g_tplvars['items'] = $items;
	render('../templates/inventory-browser.html');
}

function vendors()
{
	global $g_tplvars;
	$g_tplvars['title'] = 'Vendor List';
	$vendors = '';
	
	//Get name of statuse enum
	$r = dbquery('select `id` from enums where name = \'vendorstatus\'');
	$status = mysql_fetch_object($r)->id;
	
	//TODO: pager
	$r = dbquery('select vendors.id, vendors.name, vendors.website as website, enumvals.name as status from vendors ' .
				'inner join enumvals on vendors.status = enumvals.val and enumvals.eid = '. $status . ' order by name asc');
	while($row = mysql_fetch_assoc($r))
	{
		foreach($row as $a=>$b)
			$g_tplvars[$a] = $b;
		$vendors .= templatize('../templates/inventory-vendors-item.html');
	}
	
	$g_tplvars['vendors'] = $vendors;
	render('../templates/inventory-vendors.html');
}

function createvendor()
{
	global $g_tplvars;
	$g_tplvars['status'] = enum_list('vendorstatus');
	render('../templates/inventory-createvendor.html');
}

function docreatevendor()
{
	//Prepare input
	$name = sanitize_db(sanitize_render($_POST['name']));
	$website = sanitize_db(sanitize_render($_POST['website']));
	$status = intval($_POST['status']);
		
	//Update it
	dbquery('insert into vendors (`name`, `status`, `website`) values(\''.$name.'\', \''.$status.'\', \''.$website.'\')');
	
	//and go back to the main page
	header('Location: inventory.php?action=vendors');
}

function itemdetail()
{
	global $g_tplvars;
	$id = intval($_GET['id']);
		
	//Get name of package enum
	$r = dbquery('select `id` from enums where name = \'packages\'');
	$pkg = mysql_fetch_object($r)->id;
	$delivered = enum_name_to_value('orderstatus', 'Delivered');
	
	//Look up info for what we have in stock
	$r = dbquery('select * from items where id = ' . $id);
	if(mysql_num_rows($r))
	{
		$row = mysql_fetch_object($r);
		$g_tplvars['count'] = $row->count;
		$g_tplvars['reorder'] = $row->reorder;
		if($row->stock)
			$g_tplvars['stock'] = 'yes';
		else
			$g_tplvars['stock'] = 'no';
	}
	
	//See if we have any on order (delivered don't count)
	$onorder = 0;
	$q = dbquery('select orderitems.count from orderitems, orders where orders.status != ' . $delivered . 
				' and orderitems.order = orders.id and orderitems.item = ' . $id);
	while($x = mysql_fetch_object($q))
		$onorder += $x->count;
	$g_tplvars['onorder'] = $onorder;
	
	//Look up datasheets
	$datasheets = '';
	$r = dbquery('select datasheets.id as dsid,datasheets.title as title from datasheets,itemdatasheets where itemdatasheets.datasheet=datasheets.id and itemdatasheets.item = ' . $id . ' order by title asc');
	while($x = mysql_fetch_object($r))
	{
		$g_tplvars['title'] = $x->title;
		$g_tplvars['dsid'] = $x->dsid;
		$datasheets .= templatize('../templates/inventory-itemdetail-datasheet.html');
	}	
	$g_tplvars['datasheetlist'] = $datasheets;
	
	//Look up suppliers
	//TODO: Load all pricing info and determine who has the best deal for a given quantity
	$vendorlist = '';
	$r = dbquery('select vendoritems.vendor as vendor, vendoritems.url, vendors.name from vendoritems ' . 
				'inner join vendors on vendoritems.vendor = vendors.id where vendoritems.item = ' . $id);
	while($row = mysql_fetch_assoc($r))
	{
		//Look up price quotes
		$pr = dbquery('select `qty`, `price` from itemprices where item = ' . $id . ' and vendor = ' . $row['vendor'] . ' order by qty asc');
		$prices = '';
		while($prow = mysql_fetch_object($pr))
		{
			$g_tplvars['qty'] = $prow->qty;
			$g_tplvars['price'] = sprintf("$%.2f", $prow->price / 100);
			$g_tplvars['unitprice'] = sprintf("$%.3f", $prow->price / ($prow->qty * 100));
			$prices .= templatize('../templates/inventory-itemdetail-pricequote.html');
		}
		$g_tplvars['prices'] = $prices;
		
		foreach($row as $a=>$b)
			$g_tplvars[$a] = $b;
		$vendorlist .= templatize('../templates/inventory-itemdetail-vendor.html');
	}
	$g_tplvars['vendorlist'] = $vendorlist;
	
	//Look up generic item properties
	$r = dbquery('select items.id, items.name, enumvals.name as pack, ' . 
			'itemcats.name as category, itemsubcats.name as subcategory, '.
			'items.cat as catid, items.subcat as subcatid ' . 
			'from items, enumvals, itemcats, itemsubcats ' .
			'where items.pkg = enumvals.val and enumvals.eid = '. $pkg . ' '.
			'and itemcats.id = items.cat and itemsubcats.id = items.subcat ' .
			'and items.id = ' . $id);				
	$row = mysql_fetch_assoc($r);
	foreach($row as $a=>$b)
		$g_tplvars[$a] = $b;
	$g_tplvars['title'] = $row['category'] . ' - ' . $row['subcategory'] . ' - ' . $row['name'] . ' (' . $row['pack'] . ')';
		
	render('../templates/inventory-itemdetail.html');
}

function createvendoritem()
{
	global $g_tplvars;
	
	$id = intval($_GET['item']);
	
	//Get name of package enum
	$r = dbquery('select `id` from enums where name = \'packages\'');
	$pkg = mysql_fetch_object($r)->id;
	
	//Look up vendors
	$vendors = '';
	$r = dbquery('select `id` as value, `name` as name from vendors order by name asc');
	$g_tplvars['selected'] = '';
	while($row = mysql_fetch_assoc($r))
	{
		foreach($row as $a=>$b)
			$g_tplvars[$a] = $b;
		$vendors .= templatize('../templates/enum-selector-line.html');
	}
	$g_tplvars['vendors'] = $vendors;
	
	//Look up generic item properties
	$r = dbquery('select items.id, items.name as name, enumvals.name as pack from items ' .
				'inner join enumvals on items.pkg = enumvals.val and enumvals.eid = '. $pkg . ' where items.id = ' . $id . '');
	$row = mysql_fetch_assoc($r);
	foreach($row as $a=>$b)
		$g_tplvars[$a] = $b;
	$g_tplvars['title'] = 'Add vendor item :: ' . $row['name'] . ' (' . $row['pack'] . ')';
	$g_tplvars['id'] = $id;
	
	render('../templates/inventory-createvendoritem.html');
}

function docreatevendoritem()
{
	$id = intval($_GET['item']);
	
	//Add to DB
	$vendor = sanitize_db(sanitize_render($_POST['vendor']));
	$url = sanitize_db(sanitize_render($_POST['url']));
	dbquery('insert into vendoritems (`item`, `vendor`, `url`) values(\''.$id.'\', \''.$vendor.'\', \''.$url.'\')');
	
	//and go back to the main page
	header('Location: inventory.php?action=itemdetail&id=' . $id);
}

function createquote()
{
	global $g_tplvars;
	$vendor = intval($_GET['vendor']);
	$id = intval($_GET['item']);
	
	//Get name of package enum
	$r = dbquery('select `id` from enums where name = \'packages\'');
	$pkg = mysql_fetch_object($r)->id;
	
	//Look up vendor info
	$r = dbquery('select name from vendors where id = ' . $vendor);
	$vname = mysql_fetch_object($r)->name;
	$g_tplvars['vendor'] = $vname;
	$g_tplvars['vendorid'] = $vendor;

	//Look up generic item properties
	$r = dbquery('select items.id, items.name as name, enumvals.name as pack from items ' .
				'inner join enumvals on items.pkg = enumvals.val and enumvals.eid = '. $pkg . ' where items.id = ' . $id . '');
	$row = mysql_fetch_assoc($r);
	foreach($row as $a=>$b)
		$g_tplvars[$a] = $b;
	$g_tplvars['title'] = 'Add price quote :: ' . $row['name'] . ' (' . $row['pack'] . ')';
	
	render('../templates/inventory-createquote.html');
}

function docreatequote()
{
	//Convert price to cents
	$id = intval($_GET['item']);
	$vendor = intval($_GET['vendor']);
	$qty = intval($_POST['qty']);
	$price = intval(floatval($_POST['price']) * 100);
	
	//TODO: overwrite existing quote for this amount, if necessary
	
	//Add and go back to the main page
	dbquery('insert into itemprices (`item`, `vendor`, `qty`, `price`) values(\''.$id.'\', \''.$vendor.'\', \''.$qty.'\', \''.$price.'\')');	
	header('Location: inventory.php?action=itemdetail&id=' . $id);
}

function vendordetail()
{
	//not implemented
	die('not implemented');
}

function orders()
{
	global $g_tplvars;
	$orders = '';
	
	//Get name of enums
	$r = dbquery('select `id` from enums where name = \'orderstatus\'');
	$stat = mysql_fetch_object($r)->id;
	$r = dbquery('select `id` from enums where name = \'orderpriorities\'');
	$pri = mysql_fetch_object($r)->id;
	
	//TODO: pager
	$r = dbquery('select orders.id, vendors.id as vid, vendors.name as vendor, enumvals.name as status, evals.name as priority ' . 
				'from orders, vendors, enumvals, enumvals as evals ' .
				'where orders.vendor = vendors.id' .
				' and enumvals.val = orders.status and enumvals.eid = '. $stat . 
				' and evals.val = orders.priority and evals.eid = '. $pri . 
				' order by orders.id asc');
	while($row = mysql_fetch_assoc($r))
	{
		foreach($row as $a=>$b)
			$g_tplvars[$a] = $b;
		$orders .= templatize('../templates/inventory-orders-item.html');
	}
	
	$g_tplvars['orders'] = $orders;
	
	render('../templates/inventory-orders.html');
}

function createorder()
{
	global $g_tplvars;
	$g_tplvars['title'] = 'Create order';
	
	//Look up vendors
	$vendors = '';
	$r = dbquery('select `id` as value, `name` as name from vendors order by name asc');
	$g_tplvars['selected'] = '';
	while($row = mysql_fetch_assoc($r))
	{
		foreach($row as $a=>$b)
			$g_tplvars[$a] = $b;
		$vendors .= templatize('../templates/enum-selector-line.html');
	}
	$g_tplvars['vendors'] = $vendors;
	
	$g_tplvars['priorities'] = enum_list('orderpriorities');
	
	render('../templates/inventory-orders-create.html');
}

function docreateorder()
{
	$priority = intval($_POST['priority']);
	$vendor = intval($_POST['vendor']);
	
	$stat = enum_name_to_value('orderstatus', 'Planning');
	
	//Add and go back to the main page
	dbquery('insert into orders (`vendor`, `status`, `priority`) values(\''.$vendor.'\', \''.$status.'\', \''.$priority.'\')');	
	header('Location: inventory.php?action=orderdetail&id=' . mysql_insert_id());
}

function orderdetail()
{
	global $g_tplvars;
	$id = intval($_GET['id']);
	
	//Get name of enums
	$r = dbquery('select `id` from enums where name = \'orderstatus\'');
	$stat = mysql_fetch_object($r)->id;
	$r = dbquery('select `id` from enums where name = \'orderpriorities\'');
	$pri = mysql_fetch_object($r)->id;
	$r = dbquery('select `id` from enums where name = \'packages\'');
	$pkg = mysql_fetch_object($r)->id;
	
	$totalcount = 0;
	$totalprice = 0;
	
	//Look up all of the vendor's other orders
	$r = dbquery('select orders.vendor from orders where orders.id = ' . $id . ' limit 1');
	$row = mysql_fetch_object($r);
	$r = dbquery('select orders.id as name, orders.id as value from orders where orders.vendor = ' . $row->vendor . ' and orders.id != ' . $id);
	$orderlist = '';
	while($row = mysql_fetch_assoc($r))
	{
		foreach($row as $a=>$b)
			$g_tplvars[$a] = $b;
		$g_tplvars['selected'] = '';
		$orderlist .= templatize('../templates/enum-selector-line.html');
	}
	$g_tplvars['orderlist'] = $orderlist;
	
	//Look up order items
	$r = dbquery('select items.id as itemid, items.name, itemcats.name as cat, itemsubcats.name as subcat, enumvals.name as pkg, orderitems.count, ' .
				'(select price/qty as unitprice from itemprices where itemprices.qty <= orderitems.count and itemprices.item = items.id order by itemprices.qty desc limit 1) as unitprice ' .
				'from items, orderitems, itemcats, itemsubcats, enumvals ' .
				'where orderitems.order = ' . $id . ' ' .
				'and items.id = orderitems.item and itemcats.id = items.cat and itemsubcats.id = items.subcat ' . 
				'and enumvals.eid = ' . $pkg . ' and enumvals.val = items.pkg'
				);
	$items = '';
	while($row = mysql_fetch_assoc($r))
	{
		foreach($row as $a=>$b)
			$g_tplvars[$a] = $b;
		$itemprice = $row['count'] * $row['unitprice'] / 100.0;
		$totalprice += $itemprice;
		$totalcount += $row['count'];
		$g_tplvars['price'] = sprintf('$%.2f', $itemprice);
		$items .= templatize('../templates/inventory-orderdetail-item.html');
	}
	$g_tplvars['items'] = $items;
	
	//Look up the order
	$r = dbquery('select orders.id, vendors.id as vid, vendors.name as vendor, enumvals.name as status, evals.name as priority ' . 
				'from orders, vendors, enumvals, enumvals as evals ' .
				'where orders.vendor = vendors.id' .
				' and enumvals.val = orders.status and enumvals.eid = '. $stat . 
				' and evals.val = orders.priority and evals.eid = '. $pri . 
				' and orders.id = ' . $id . ' limit 1');
	$row = mysql_fetch_assoc($r);
	foreach($row as $a=>$b)
		$g_tplvars[$a] = $b;
	$g_tplvars['totalcount'] = $totalcount;
	$g_tplvars['totalprice'] = sprintf('$%.2f', $totalprice);	
	$g_tplvars['title'] = 'Order ' . $row['id'] . ' (from ' . $row['vendor'] . ')';
	
	render('../templates/inventory-orderdetail.html');
}

function addorderitem()
{
	global $g_tplvars;
	$order = intval($_GET['order']);
	
	//Get name of package enum
	$r = dbquery('select `id` from enums where name = \'packages\'');
	$pkg = mysql_fetch_object($r)->id;
	
	//Look up the order
	$r = dbquery('select vendors.id as vid, vendors.name as vendor ' . 
				'from orders, vendors' .
				' where orders.vendor = vendors.id' .
				' and orders.id = ' . $order);
	$row = mysql_fetch_assoc($r);
	foreach($row as $a=>$b)
		$g_tplvars[$a] = $b;
	$g_tplvars['title'] = 'Add to order ' . $order . ' (from ' . $row['vendor'] . ')';	
	
	//Look up items sold by this vendor
	$items = '';
	$vendor = $row['vid'];
	$r = dbquery('select items.id, items.name, enumvals.name as pkg' .
				' from items, vendoritems, enumvals' .
				' where items.id = vendoritems.item' .
				' and vendoritems.vendor = ' . $vendor .
				' and enumvals.eid = ' . $pkg . ' and enumvals.val = items.pkg' .
				' order by name asc'
				);
	while($row = mysql_fetch_object($r))
	{
		$g_tplvars['name'] = $row->name . ' (' . $row->pkg . ')';
		$g_tplvars['value'] = $row->id;
		$g_tplvars['selected'] = '';
		$items .= templatize('../templates/enum-selector-line.html');
	}
	$g_tplvars['items'] = $items;
	
	$g_tplvars['order'] = $order;
	render('../templates/inventory-orders-additem.html');
}

function doaddorderitem()
{
	$order = intval($_GET['order']);
	$item = intval($_POST['item']);
	$qty = intval($_POST['qty']);
	
	//Add and go back to the main page
	dbquery('insert into orderitems (`item`, `order`, `count`) values(\''.$item.'\', \''.$order.'\', \''.$qty.'\')');	
	header('Location: inventory.php?action=orderdetail&id=' . $order);
}

function datasheets()
{
	global $g_tplvars;
	$sheets = '';
	
	$r = dbquery('select * from datasheets order by title asc');
	while($row = mysql_fetch_assoc($r))
	{
		foreach($row as $a=>$b)
			$g_tplvars[$a] = $b;
		$sheets .= templatize('../templates/inventory-datasheets-item.html');
	}
	
	$g_tplvars['datasheets'] = $sheets;	
	render('../templates/inventory-datasheets.html');
}

function datasheetdownload()
{
	$id = intval($_GET['id']);
	$r = dbquery('select path from datasheets where id = ' . $id . ' limit 1');
	$row = mysql_fetch_object($r);
	$fname = $row->path;
	
	//TODO: better directory traversal protection (don't hard-code the safe path)
	if(substr_count($fname, '/nfs/share/datasheets') != 1 || substr_count($fname, '..') > 0)
		die('bad filename');
		
	$info = pathinfo($fname);
	header('Content-Type: application/pdf');
	header('Content-Length: ' . filesize($fname));
	header('Content-Disposition: attachment; filename=' . urlencode($info['basename']));
	readfile($fname);
}

function createdatasheet()
{
	global $g_tplvars;
	
	$skips = array();
	$r = dbquery('select path from datasheets');
	while($row = mysql_fetch_object($r))
		$skips[$row->path] = 1;
	
	$g_tplvars['paths'] = pathlist('/nfs/share/datasheets', $skips);
	render('../templates/inventory-datasheets-create.html');
}

function docreatedatasheet()
{
	//TODO: better directory traversal protection (don't hard-code the safe path)
	$fname = sanitize_db($_POST['path']);
	if(substr_count($fname, '/nfs/share/datasheets') != 1)
		die('bad filename - bad root');
	if(substr_count($fname, '..') > 0)
		die('bad filename - dir traversal');
	if(!file_exists($fname))
		die('bad filename - nonexistent');
		
	$title = sanitize_db(sanitize_render($_POST['title']));
	if($title == '')
	{
		$info = pathinfo($fname);
		$title = str_replace('.pdf', '', $info['basename']);
	}
	
	dbquery('insert into datasheets (`title`,`path`) values(\'' . $title . '\', \'' . $fname . '\')');
	
	header('Location: ?action=datasheets');
}

function createitemdatasheet()
{
	global $g_tplvars;
	$sheets = '';
	
	$item = intval($_GET['item']);
	
	$g_tplvars['selected'] = '';
	$r = mysql_query(
		'select `id` as value, `title` as name, ' . 
		'(select count(datasheet) from itemdatasheets where item = ' . $item . ' and datasheet = datasheets.id) as ct ' .
		'from datasheets order by `title` asc'
		);
	while($row = mysql_fetch_assoc($r))
	{
		if($row['ct'] != 0)
			continue;
		foreach($row as $a=>$b)
			$g_tplvars[$a] = $b;
		$sheets .= templatize('../templates/enum-selector-line.html');
	}
	
	$g_tplvars['datasheets'] = $sheets;
	$g_tplvars['item'] = $item;
	render('../templates/inventory-itemdatasheets-create.html');
}

function docreateitemdatasheet()
{
	$datasheet = intval($_POST['datasheet']);
	$item = intval($_POST['item']);
	
	dbquery('insert into itemdatasheets (`item`,`datasheet`) values(\'' . $item . '\', \'' . $datasheet . '\')');
	
	header('Location: ?action=itemdetail&id=' . $item);
}

function moveorderitem()
{
	$oldorder = intval($_POST['oldorder']);
	$neworder = intval($_POST['neworder']);
	$itemid = intval($_POST['itemid']);
	dbquery("update orderitems set `order` = $neworder where `item` = $itemid and `order` = $oldorder limit 1");
	
	header("Location: inventory.php?action=orderdetail&id=$neworder");
}
?>
